#! /bin/bash
# 更新
string1="你的系统暂时不支持！"
string2="请按下任意键退出..."
function package_manage {
	system_info="$(cat /etc/os-release)"
	if echo "$system_info" | grep -q "ID=alpine";
	then
		apk update && apk upgrade
		apk add $@
	elif echo "$system_info" | grep -qE "ID=kali|ID=debian|ID=ubuntu";
	then
		apt update && apt full-upgrade -y
		apt install $@ -y
	else
		echo "$string1"
		read -p "$string2" -n 1 -s
		exit 1
	fi
}
# 安装zsh
echo "程序正在运行中..."
package_manage zsh wget openssh-server
# 使用 wget 下载脚本并安装
sh -c "$(wget https://gitee.com/aiba51/linux-One-click-installation-ohmyzsh/releases/download/v0.1/install.sh -O -)"
status=$?
# 安装插件
# 1.zsh-autosuggestions
# 2.zsh-syntax-highlighting
# 3.z
if [ "$status" -eq 0 ]; then
	git clone https://gitee.com/aiba51/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions
	status_a=$?
	git clone https://gitee.com/aiba51/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting
	status_b=$?
else
	echo "oh-my-zsh 安装失败,请重试！"
	exit 1
fi
# 设置
zshrc="/root/.zshrc"
old_1='ZSH_THEME="robbyrussell"'
new_1='ZSH_THEME="random"'
old_2="plugins=(git)"
new_2="plugins=(git zsh-autosuggestions zsh-syntax-highlighting z)"
# 设置ssh服务启动别名"sshd"
ssh_alias="alias sshd='/usr/sbin/sshd'"
if [ "$status_a" -eq 0 ] && [ "$status_b" -eq 0 ]; then
	if cat "$zshrc" | grep -q "$new_1" && grep -q "$new_2" && grep -q "$ssh_alias"; then
		echo "zshrc 文件已经是最新设置！"
	else
		echo "正在设置 zshrc 文件..."
		sed -i -e "s|$old_1|$new_1|" -e "s|$old_2|$new_2|" -e "\$a$ssh_alias" "$zshrc"
	fi
else
	echo "插件克隆失败，请重试！"
	exit 1
fi
# 设置zsh为默认shell
file="/etc/passwd"
zsh_install_dir_usr=$(which zsh)
zsh_install_dir_system="/bin/zsh"
old_a="root:x"
new_a="root:x:0:0:root:/root:$zsh_install_dir_usr"
if cat "$file" | grep -qE "$zsh_install_dir_usr|$zsh_install_dir_system"; then
	echo "默认shell是zsh"
else
	echo "正在设置默认shell为zsh"
	sed -i "/^$old_a/s/^/# /" "$file"
	sed -i "/^# $old_a/a $new_a" "$file"
fi
cp "install.sh" "upgrade.sh" /root/.oh-my-zsh/tools
source "$zshrc"
run_sshd_dir="/run/sshd"
if [[ -d "$run_sshd_dir" ]]; then
	echo "目录 $run_sshd_dir 已经存在。"
else
	echo "正在创建目录 $run_sshd_dir ..."
	mkdir "$run_sshd_dir"
fi
